package jmine.tec.utils.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * FactoryBean capaz de buscar um bean que se encontra em outra bean factory, desde que esta seja um singleton.
 * 
 * @author lundberg
 */
public class SingletonContextBeanFactoryBean implements FactoryBean {

    private String selector;

    private String factoryKey;

    private String name;

    private Class objectType;

    private boolean singleton;

    /**
     * {@inheritDoc}
     */
    public Object getObject() throws Exception {
        BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance(this.selector);
        BeanFactoryReference reference = locator.useBeanFactory(this.factoryKey);
        BeanFactory beanFactory = reference.getFactory();
        return beanFactory.getBean(this.name, this.objectType);
    }

    /**
     * {@inheritDoc}
     */
    public Class getObjectType() {
        return this.objectType;
    }

    /**
     * {@inheritDoc}
     */
    public boolean isSingleton() {
        return this.singleton;
    }

    /**
     * @param selector the selector to set
     */
    public void setSelector(String selector) {
        this.selector = selector;
    }

    /**
     * @param factoryKey the factoryKey to set
     */
    public void setFactoryKey(String factoryKey) {
        this.factoryKey = factoryKey;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @param objectType the objectType to set
     */
    public void setObjectType(Class objectType) {
        this.objectType = objectType;
    }

    /**
     * @param singleton the singleton to set
     */
    public void setSingleton(boolean singleton) {
        this.singleton = singleton;
    }
}
